package com.niit.scs.server.service.impl;

import com.niit.scs.server.doc.EsContentInfo;
import com.niit.scs.server.domain.UserAccount;
import com.niit.scs.server.repository.EsContentInfoRepository;
import com.niit.scs.server.repository.UserAccountRepository;
import com.niit.scs.server.service.ContentInfoService;
import com.niit.scs.server.domain.ContentInfo;
import com.niit.scs.server.repository.ContentInfoRepository;
import liquibase.pro.packaged.G;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.geo.GeoPoint;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;

/**
 * Service Implementation for managing {@link ContentInfo}.
 */
@Service
@Transactional
public class ContentInfoServiceImpl implements ContentInfoService {

    private final Logger log = LoggerFactory.getLogger(ContentInfoServiceImpl.class);

    private final ContentInfoRepository contentInfoRepository;
    private final UserAccountRepository userAccountRepository;
    private final EsContentInfoRepository esContentInfoRepository;

    private final JdbcTemplate jdbcTemplate;

    public ContentInfoServiceImpl(ContentInfoRepository contentInfoRepository, JdbcTemplate jdbcTemplate, UserAccountRepository userAccountRepository, EsContentInfoRepository esContentInfoRepository) {
        this.contentInfoRepository = contentInfoRepository;
        this.jdbcTemplate = jdbcTemplate;
        this.userAccountRepository = userAccountRepository;
        this.esContentInfoRepository = esContentInfoRepository;
    }

    @Override
    public ContentInfo save(String login,ContentInfo contentInfo) {
        log.debug("Request to save ContentInfo : {}", contentInfo);
        //新增状态
        if(contentInfo.getId()==null){
            //发布时间
            contentInfo.setContentTime(ZonedDateTime.now());
            //点赞数、评论数、收藏数初始化为0
            contentInfo.setContentPraiseCount(0l);
            contentInfo.setContentFavorateCount(0l);
            contentInfo.setContentCommentCount(0l);
            UserAccount account=this.userAccountRepository.findByLogin(login);
            contentInfo.setAccount(account);
        }
        return contentInfoRepository.save(contentInfo);
    }

    @Override
    @Transactional(readOnly = true)
    public Page<ContentInfo> findAll(Pageable pageable) {
        log.debug("Request to get all ContentInfos");
        return contentInfoRepository.findAll(pageable);
    }


    @Override
    @Transactional(readOnly = true)
    public Optional<ContentInfo> findOne(Long id) {
        log.debug("Request to get ContentInfo : {}", id);
        return contentInfoRepository.findById(id);
    }

    @Override
    public void delete(String login,Long id) throws Exception {
        log.debug("Request to delete ContentInfo : {}", id);
        Optional<ContentInfo> contentInfoOptional=contentInfoRepository.findById(id);
        if(contentInfoOptional.isPresent()){
            ContentInfo contentInfo=contentInfoOptional.get();
            if(contentInfo.getAccount()!=null
                && contentInfo.getAccount().getLogin()!=null
                && contentInfo.getAccount().getLogin().equals(login)){
                contentInfoRepository.deleteById(id);
            }else{
                throw new Exception("ID为"+id+"的数据不属于当前登录用户"+login);
            }
        }else{
            throw new Exception("未找到ID为"+id+"的数据");
        }

    }

    @Override
    public Page<ContentInfo> getContentByTypeName(String typeName, Integer index, Integer size) {
//        String sql="select " +
//            "    a.*,b.content_type_name " +
//            "from " +
//            "    content_info a,content_type b " +
//            "where " +
//            "    a.content_type_id=b.id ";
//        if(typeName!=null && typeName.length()>0){
//            sql+=" and b.content_type_name='"+typeName+"'";
//        }
//        Integer start=index*size;
//        Integer end=start+size;
//        sql+=" limit "+start+","+end;
//        List<Map<String,Object>> sqlResult=this.jdbcTemplate.queryForList(sql);
//        //List<Map<String,Object>>---->List<ContentInfo>
//        List<ContentInfo> result=new ArrayList<ContentInfo>();
//        if(sqlResult!=null && !sqlResult.isEmpty()){
//            for (Map<String, Object> sqlItem : sqlResult) {
//                ContentInfo contentInfo=new ContentInfo();
//                contentInfo.setId(TypeUtils.castToLong(sqlItem.get("id")));
//                contentInfo.setContentActor(TypeUtils.castToString(sqlItem.get("content_actor")));
//                contentInfo.setContentCommentCount(TypeUtils.castToLong(sqlItem.get("content_comment_count")));
//                contentInfo.setContentFavorateCount(TypeUtils.castToLong(sqlItem.get("content_favorate_count")));
//                contentInfo.setContentImg(TypeUtils.castToString(sqlItem.get("content_img")));
//                contentInfo.setContentInfo(TypeUtils.castToString(sqlItem.get("content_info")));
//                ContentType contentType=new ContentType();
//                contentType.setId(TypeUtils.castToLong(sqlItem.get("content_type_id")));
//                contentType.setContentTypeName(TypeUtils.castToString(sqlItem.get("content_type_name")));
//                contentInfo.setContentType(contentType);
//
//                result.add(contentInfo);
//            }
//        }
//        String totalSql="select " +
//            "    count(1) totalcount " +
//            "from " +
//            "    content_info a,content_type b " +
//            "where " +
//            "    a.content_type_id=b.id ";
//        if(typeName!=null && typeName.length()>0){
//            totalSql+=" and b.content_type_name='"+typeName+"'";
//        }
//        List<Map<String,Object>> totalResult=
//            this.jdbcTemplate.queryForList(totalSql);
//        Long totalCount=0l;
//        if(totalResult!=null && !totalResult.isEmpty()){
//            Map<String,Object> item=totalResult.get(0);
//            totalCount=TypeUtils.castToLong(item.get("totalcount"));
//        }
//        return new PageImpl(result, PageRequest.of(index,size),totalCount);

        Page<ContentInfo> result=this.contentInfoRepository
            .findByContentTypeContentTypeName(typeName,PageRequest.of(index,size));
        return result;
    }

    @Override
    public Page<ContentInfo> getAllContent(
        String keyword,
        String typeName,
        Integer index,
        Integer size) {
        keyword="%"+keyword+"%";
        Page<ContentInfo> result=null;
//        if(typeName.equals("ALL")){
//            result=this.contentInfoRepository.findByContentInfoLike(keyword,PageRequest.of(index,size));
//        }else{
//            result=this.contentInfoRepository
//                .findByContentInfoLikeAndContentTypeContentTypeName(keyword,typeName,PageRequest.of(index,size));
//        }
        result=this.contentInfoRepository.getAllContent(keyword,typeName,PageRequest.of(index,size));
        return result;
    }

    @Override
    public Page<ContentInfo> getSubContent(String login, String keywords, Integer index, Integer size) {
        keywords="%"+keywords+"%";
        Page<ContentInfo> result=this.contentInfoRepository.getSubContent(login,keywords,PageRequest.of(index,size));
        return result;
    }

    @Override
    public Page<ContentInfo> myPraise(String login, Integer index, Integer size) {
        Page<ContentInfo> result=this.contentInfoRepository.getMyPraise(login, PageRequest.of(index,size));
        return result;
    }

    @Override
    public Page<ContentInfo> myFavorite(String login, Integer index, Integer size) {
        Page<ContentInfo> result=this.contentInfoRepository.getMyFavorite(login,PageRequest.of(index,size));
        return result;
    }

    @Override
    public Page<ContentInfo> myContent(String login, Integer index, Integer size) {
        Page<ContentInfo> result=this.contentInfoRepository.findByAccountLogin(login,PageRequest.of(index,size));
        return result;
    }

    @Override
    public Page<EsContentInfo> getContentFromEs(String text,Integer index,Integer size) {
        Page<EsContentInfo> result=this.esContentInfoRepository.findByContenttext(text,PageRequest.of(index,size));
        return result;
    }

    @Override
    public List<EsContentInfo> updateContentPosition() {
        //创建10个坐标点
        Float [][] pos={
            {118.942225f,32.119945f},
            {118.943834f,32.121099f},
            {118.943582f,32.119514f},
            {118.939243f,32.120759f},
            {118.943207f,32.118146f},
            {118.941823f,32.118092f},
            {118.940171f,32.118151f},
            {118.943845f,32.117664f},
            {118.937209f,32.119677f}
        };
        //使用10个坐标点初始化生成40个坐标对象
        List<GeoPoint> points=new ArrayList<GeoPoint>();
        for(int i=0;i<40;i++){
            int arrpos=i%10;
            points.add(new GeoPoint(pos[arrpos][1],pos[arrpos][0]));
        }
        Iterable<EsContentInfo> esIterable=this.esContentInfoRepository.findAll();
        Integer i=0;
        List<EsContentInfo> result=new ArrayList<EsContentInfo>();
        Iterator<EsContentInfo> esContentInfoIterator=esIterable.iterator();
        while(esContentInfoIterator.hasNext()) {
            EsContentInfo contentInfo = esContentInfoIterator.next();
            contentInfo.setContentposition(new GeoPoint(points.get(i).getLat(), points.get(i).getLon()));
            contentInfo=this.esContentInfoRepository.save(contentInfo);
            result.add(contentInfo);
        }
        return result;
    }

}
